<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="druid,CannotGetJdbcConnectionException,hystrix,中断,排查" />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="写在前面最近线上数据库连接池报获取连接超时，一开始没怎么注意，后来异常的数量变多了，就找了时间来查查。发现了一个比较有意思的问题，记录下来。 异常1### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection;">
<meta name="keywords" content="druid,CannotGetJdbcConnectionException,hystrix,中断,排查">
<meta property="og:type" content="article">
<meta property="og:title" content="记一次Druid连接池CannotGetJdbcConnectionException问题排查">
<meta property="og:url" content="http://www.zhizus.com/2018-07-16-记一次Druid连接池CannotGetJdbcConnectionException问题排查.html">
<meta property="og:site_name" content="郑大侠的博客">
<meta property="og:description" content="写在前面最近线上数据库连接池报获取连接超时，一开始没怎么注意，后来异常的数量变多了，就找了时间来查查。发现了一个比较有意思的问题，记录下来。 异常1### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-07-16T09:57:37.319Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="记一次Druid连接池CannotGetJdbcConnectionException问题排查">
<meta name="twitter:description" content="写在前面最近线上数据库连接池报获取连接超时，一开始没怎么注意，后来异常的数量变多了，就找了时间来查查。发现了一个比较有意思的问题，记录下来。 异常1### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: "",
      labels: ""
    }
  };
</script>



  <link rel="canonical" href="http://www.zhizus.com/2018-07-16-记一次Druid连接池CannotGetJdbcConnectionException问题排查.html"/>





  <title> 记一次Druid连接池CannotGetJdbcConnectionException问题排查 | 郑大侠的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f75c9cec9ecead0dfce9a108b9688072";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑大侠的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-crossed">
          <a href="http://zhizus.com" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-camera-retro"></i> <br />
            
            穿越
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-case " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://www.zhizus.com/2018-07-16-记一次Druid连接池CannotGetJdbcConnectionException问题排查.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="DempeZheng">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑大侠的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                记一次Druid连接池CannotGetJdbcConnectionException问题排查
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          
          
             <span id="/2018-07-16-记一次Druid连接池CannotGetJdbcConnectionException问题排查.html" class="leancloud_visitors" data-flag-title="记一次Druid连接池CannotGetJdbcConnectionException问题排查">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="写在前面"><a href="#写在前面" class="headerlink" title="写在前面"></a>写在前面</h2><p>最近线上数据库连接池报获取连接超时，一开始没怎么注意，后来异常的数量变多了，就找了时间来查查。发现了一个比较有意思的问题，记录下来。</p>
<h2 id="异常"><a href="#异常" class="headerlink" title="异常"></a>异常</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 2000, active 32, runningSqlCount 1</span><br></pre></td></tr></table></figure>
<h2 id="排查思路"><a href="#排查思路" class="headerlink" title="排查思路"></a>排查思路</h2><p>从异常信息来看是连接池拿连接超时，这里有两种可能。
1）数据库连接已经用完，应用层获取不到连接；
2）druid连接池连接已经达到maxActive值</p>
<p>下面命令可以查看db连接池的最大值：
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">show</span> <span class="keyword">variables</span> <span class="keyword">like</span> <span class="string">'%max_connections%'</span>;</span><br></pre></td></tr></table></figure></p>
<p>发现这个值其实还挺大，用完的概率不大。
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">+-----------------+-------+</span><br><span class="line">| Variable_name   | Value |</span><br><span class="line">+-----------------+-------+</span><br><span class="line">| max_connections | 5000  |</span><br><span class="line">+-----------------+-------+</span><br></pre></td></tr></table></figure></p>
<p>另外，查看网上，数据库连接用完，异常信息应该是Too many connections 类似的信息（这个没有去验证），所以基本上可以排除是db的连接的原因。</p>
<p>所以大概率是druid连接池达到的最大值maxActive，</p>
<p>这个达到最大值有两个可能，第一种是maxActive配置的太小，并发请求太多。第二种就是某种特定的场景有连接泄露。</p>
<p>到这里基本上没有太好的思路去验证到底是哪种原因导致的了。</p>
<p>首先想到的就是maxActive太小，我们配置的是32，在网络抖动的时候，并发量较大的场景，是有可能会耗完连接的。</p>
<p>如果是连接泄露，应该会有相关异常，搜索exception日志发现如下异常：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">05:22:33 ERROR version_IS_UNDEFINED [89d552dc1f074730bb5c6459bc58101e][hystrix-ADD_BEAN_CHANGELOG_VALIDATOR-4]c.a.d.p.DruidDataSource - recyle error?</span><br><span class="line">java.lang.InterruptedException: null</span><br><span class="line">        at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1220) ~[na:1.8.0_40]</span><br><span class="line">        at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335) ~[na:1.8.0_40]</span><br><span class="line">        at com.alibaba.druid.pool.DruidDataSource.recycle(DruidDataSource.java:1266) ~[druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.pool.DruidPooledConnection.recycle(DruidPooledConnection.java:292) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.filter.FilterChainImpl.dataSource_recycle(FilterChainImpl.java:4534) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.filter.stat.StatFilter.dataSource_releaseConnection(StatFilter.java:646) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.filter.FilterChainImpl.dataSource_recycle(FilterChainImpl.java:4530) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.filter.FilterAdapter.dataSource_releaseConnection(FilterAdapter.java:2717) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.filter.FilterChainImpl.dataSource_recycle(FilterChainImpl.java:4530) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at com.alibaba.druid.pool.DruidPooledConnection.close(DruidPooledConnection.java:240) [druid-1.0.9.jar:1.0.9]</span><br><span class="line">        at org.springframework.jdbc.datasource.DataSourceUtils.doCloseConnection(DataSourceUtils.java:341) [spring-jdbc-4.3.8.RELEASE.jar:4.3.8.RELEASE]</span><br><span class="line">        at org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:328) [spring-jdbc-4.3.8.RELEASE.jar:4.3.8.RELEASE]</span><br><span class="line">        at org.springframework.jdbc.datasource.DataSourceUtils.releaseConnection(DataSourceUtils.java:294) [spring-jdbc-4.3.8.RELEASE.jar:4.3.8.RELEASE]</span><br><span class="line">        at org.mybatis.spring.transaction.SpringManagedTransaction.close(SpringManagedTransaction.java:127) [mybatis-spring-1.2.3.jar:1.2.3]</span><br><span class="line">        at org.apache.ibatis.executor.BaseExecutor.close(BaseExecutor.java:88) [mybatis-3.3.0.jar:3.3.0]</span><br><span class="line">        at org.apache.ibatis.executor.CachingExecutor.close(CachingExecutor.java:63) [mybatis-3.3.0.jar:3.3.0]</span><br><span class="line">        at sun.reflect.GeneratedMethodAccessor106.invoke(Unknown Source) ~[na:na]</span><br><span class="line">        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_40]</span><br><span class="line">        at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_40]</span><br><span class="line">        at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:63) [mybatis-3.3.0.jar:3.3.0]</span><br><span class="line">        at com.sun.proxy.$Proxy182.close(Unknown Source) [na:na]</span><br><span class="line">        at org.apache.ibatis.session.defaults.DefaultSqlSession.close(DefaultSqlSession.java:236) [mybatis-3.3.0.jar:3.3.0]</span><br><span class="line">        at org.mybatis.spring.SqlSessionUtils.closeSqlSession(SqlSessionUtils.java:195) [mybatis-spring-1.2.3.jar:1.2.3]</span><br><span class="line">        at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:407) [mybatis-spring-1.2.3.jar:1.2.3]</span><br><span class="line">        at com.sun.proxy.$Proxy73.selectOne(Unknown Source) [na:na]</span><br><span class="line">        at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:165) [mybatis-spring-1.2.3.jar:1.2.3]</span><br><span class="line">        at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:69) [mybatis-3.3.0.jar:3.3.0]</span><br><span class="line">        at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:53) [mybatis-3.3.0.jar:3.3.0]</span><br><span class="line">        at com.sun.proxy.$Proxy119.queryUserChangeAccountLog(Unknown Source) [na:na]</span><br><span class="line">        at manager.hystrix.ChangeLogCommand.getChangeLogEntity(ChangeLogCommand.java:51) [platform_consume_service.jar:na]</span><br><span class="line">        at manager.hystrix.ChangeLogCommand.run(ChangeLogCommand.java:39) [platform_consume_service.jar:na]</span><br><span class="line">        at manager.hystrix.ChangeLogCommand.run(ChangeLogCommand.java:14) [platform_consume_service.jar:na]</span><br><span class="line">        at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:302) [hystrix-core-1.5.12.jar:1.5.12]</span><br><span class="line">        at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:298) [hystrix-core-1.5.12.jar:1.5.12]</span><br><span class="line">        at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) [rxjava-1.2.0.jar:1.2.0]</span><br><span class="line">        at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) [rxjava-1.2.0.jar:1.2.0]</span><br></pre></td></tr></table></figure>
<p>查看源代码，可以发现是由于：
hystrix降级的时候抛出了Interupted异常，导致DruidDataSource.recycle()回收中断。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">final</span> <span class="keyword">long</span> lastActiveTimeMillis = System.currentTimeMillis();</span><br><span class="line">       lock.lockInterruptibly();<span class="comment">// 这里会响应线程中断，hystrix降级会中断当前线程，</span></span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           activeCount--;</span><br><span class="line">           closeCount++;</span><br><span class="line"></span><br><span class="line">           putLast(holder, lastActiveTimeMillis);</span><br><span class="line">           recycleCount++;</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           lock.unlock();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">       holder.clearStatementCache();</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span> (!holder.isDiscard()) &#123;</span><br><span class="line">           <span class="keyword">this</span>.discardConnection(physicalConnection);<span class="comment">//抛弃连接，不进行回收，而是抛弃</span></span><br><span class="line">           holder.setDiscard(<span class="keyword">true</span>);</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       LOG.error(<span class="string">"recyle error"</span>, e);</span><br><span class="line">       recycleErrorCount.incrementAndGet();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>
<p>乍一看，貌似是这里的问题，在回收程序里面出现中断，导致回收逻辑没有处理完。
但是，这个不一定是根本原因，继续看，catch里面的代码，druid将这个hold给Discard。也就是回收逻辑有一层catch保护。
继续看<code>discardConnection</code>做了哪些工作？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">discardConnection</span><span class="params">(Connection realConnection)</span> </span>&#123;</span><br><span class="line">        JdbcUtils.close(realConnection);<span class="comment">//关掉连接</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            lock.lockInterruptibly();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            LOG.error(<span class="string">"interrupt"</span>);</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            activeCount--;</span><br><span class="line">            discardCount++;</span><br><span class="line"></span><br><span class="line">            <span class="keyword">if</span> (activeCount &lt;= <span class="number">0</span>) &#123;</span><br><span class="line">                emptySignal();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>这里可以清晰的看到，这个连接会被close掉，然后抛弃。所以这个连接回收不存在连接泄露。</p>
<p>尽管没有连接泄露，但是这个连接没有正常回收，被抛弃了。总归还不是太好。毕竟创建连接也挺耗。</p>
<p>所以，怎么解决由hystirx线程中断导致druid连接回收异常的问题呢？</p>
<h3 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h3><h4 id="hystrix降级但是不中断当前线程"><a href="#hystrix降级但是不中断当前线程" class="headerlink" title="hystrix降级但是不中断当前线程"></a>hystrix降级但是不中断当前线程</h4><p>hystrix设置：
execution.isolation.thread.interruptOnTimeout（是否打开超时线程中断）设置false。</p>
<p>能够避免druid因为线程中断造成连接回收失败造成的问题。但是不是最好的方式。
毕竟已经降级，继续执行当前线程其实是浪费资源。</p>
<h4 id="升级druid版本"><a href="#升级druid版本" class="headerlink" title="升级druid版本"></a>升级druid版本</h4><p>这个问题的根本原因还是因为druid 实现的原因，不理解为什么druid要调用Lock.lockInterruptibly()这个方法来加锁，</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">void</span> <span class="title">acquireInterruptibly</span><span class="params">(<span class="keyword">int</span> arg)</span></span></span><br><span class="line"><span class="function">          <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (Thread.interrupted())</span><br><span class="line">          <span class="keyword">throw</span> <span class="keyword">new</span> InterruptedException();</span><br><span class="line">      <span class="keyword">if</span> (!tryAcquire(arg))</span><br><span class="line">          doAcquireInterruptibly(arg);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>释放连接的逻辑应该是要保证一定能释放，所以理论上是要直接调用Lock.lock()方法，不接受中断就好了。
当然最新的版本上已经是这么实现了。
所以升级到最新的版本就好了。</p>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>由于hystrix降级线程中断，导致druid连接回收异常并不会造成连接泄露，所以大量的<code>GetConnectionTimeoutException</code>很可能不是这个原因造成的。</p>
<p>可能是网络抖动造成sql时延上涨，从而导致连接不够用；
也可能是db抖动导致时延上涨，</p>
<p>上面的原因一时间都不太好排查，目前先解决已经发现的问题，后面持续跟踪。<br>1）调大连接池数量，这个一定程度上可以缓解问题，减少异常数量<br>2）修复hystrix 中断导致连接回收异常</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        
  <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
    <div>大侠劫富济贫啦！</div>
    <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
      <span>赏</span>
    </button>
    <div id="QR" style="display: none;">
      
        <div id="wechat" style="display: inline-block">
          <img id="wechat_qr" src="/images/dempe/20180527112524.jpg" alt="DempeZheng WeChat Pay"/>
        </div>
      
      
    </div>
  </div>


      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018-07-11-浅谈CPU缓存一致性协议MESI.html" rel="next" title="CPU缓存一致性协议MESI">
                <i class="fa fa-chevron-left"></i> CPU缓存一致性协议MESI
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018-07-29-InnoDB Checkpoint机制.html" rel="prev" title="InnoDB的Checkpoint机制">
                InnoDB的Checkpoint机制 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="SOHUCS"></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="https://avatars3.githubusercontent.com/u/6263631?v=3&s=466"
               alt="DempeZheng" />
          <p class="site-author-name" itemprop="name">DempeZheng</p>
           
              <p class="site-description motion-element" itemprop="description">請更固執，將自己謀生與擅長的事情做到最好</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">68</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/dempeZheng" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://music.163.com/#/user/home?id=6758793" target="_blank" title="网易云音乐">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  网易云音乐
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.zhihu.com/people/dempe" target="_blank" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              Links
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.wolfbe.com/" title="朗度云" target="_blank">朗度云</a>
                </li>
              
            </ul>
          </div>
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#写在前面"><span class="nav-number">1.</span> <span class="nav-text">写在前面</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异常"><span class="nav-number">2.</span> <span class="nav-text">异常</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#排查思路"><span class="nav-number">3.</span> <span class="nav-text">排查思路</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#解决方案"><span class="nav-number">3.1.</span> <span class="nav-text">解决方案</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#hystrix降级但是不中断当前线程"><span class="nav-number">3.1.1.</span> <span class="nav-text">hystrix降级但是不中断当前线程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#升级druid版本"><span class="nav-number">3.1.2.</span> <span class="nav-text">升级druid版本</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">4.</span> <span class="nav-text">总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">DempeZheng</span>
</div>



        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  






  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  


  




	





  





  





  






  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.1.js"></script>
  <script>AV.initialize("dhzMp0HdJLWMCrt04bwybWzH-gzGzoHsz", "gH6FmxJiUaVLLRXQDWpkkIVv");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

</body>
</html>
